﻿@model NAccounting.Models.LotDetailModel

@{
    ViewBag.Title = "Edit";
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>

<script language="javascript">

    $(function () {
        var hasOpenDate = @Model.HasOpenDate.ToString().ToLower();
        var periodStart = "@Model.PeriodStartJs";
        var periodEnd = "@Model.PeriodEndJs";
        var closeLotUrl = '@Url.Action("Close", "Lot", new { Id = Model.Id })';
        var getReleases = '@Url.Action("GetByLot", "AccountEntry")'
        var createAccountingEntryUrl = '@Url.Action("Create", "AccountEntry", new { Lot = Model.Id })';
        var canCreateLotForDate = '@Url.Action("CanCreateLotForDate")';
        var goBackUrl = '@Url.Action("Index")';
        var modelId = @Model.Id;
        var lotIsBalanced = @Model.IsBalanced.ToString().ToLower();

        if (hasOpenDate == false){
            var dates = $("#PeriodStartCalendar, #PeriodEndCalendar").datepicker({
                showButtonPanel: true,
                changeMonth: true,
                numberOfMonths: 1,
                onSelect: function (selectedDate) {
                    var option = this.id == "PeriodStartCalendar" ? "minDate" : "maxDate",
					    instance = $(this).data("datepicker"),
					    date = $.datepicker.parseDate(
						    instance.settings.dateFormat ||
						    $.datepicker._defaults.dateFormat,
						    selectedDate, instance.settings);
                    dates.not(this).datepicker("option", option, date);

                    var t = new loader();
                    t.show();

                    $.getJSON(canCreateLotForDate, 
                          { date: selectedDate }, 
                          function (result){

                            t.hide();

                            if (!result.canCreateLotForDate)
                            {
                                $("#dateInvalidMessageContainer").show('slow');
                                $("#saveButton").attr('disabled', 'disabled');
                                $("#saveAndOpenLotButton").attr('disabled', 'disabled');
                            }
                            else
                            {
                                $("#saveButton").removeAttr('disabled');
                                $("#saveAndOpenLotButton").removeAttr('disabled');
                                $("#dateInvalidMessageContainer").hide();
                            }
                          });
                }
            });

            $('#PeriodStartCalendar').datepicker('option', { altField: "#PeriodStart", maxDate: new Date() });
            $('#PeriodEndCalendar').datepicker('option', { altField: "#PeriodEnd", minDate: new Date() });

            $('#PeriodStartCalendar').datepicker('setDate', new Date(periodStart));
            $('#PeriodEndCalendar').datepicker('setDate', new Date(periodEnd));    
        }

        $("#releasesGrid").jqGrid({
            datatype: "json",
            postData: {
                LotId: function (){ return modelId;}
            },
            url: getReleases,
            caption: "Lançamentos",
            mtype: 'GET',
            rowNum: 10,
            rowList: [10, 20, 30],
            height: 275,
            pager: '#releasesPager',
            sortname: 'Description',
            sortorder: "desc",
            colNames: ["id", "", "Descrição", "Plano de Contas", "Tipo", "Data", "Valor", "canEdit"],
            colModel: [{ name: "Id", width: 1, hidden: true, key: true },
                       { name: "actions", width: 8, hidden: true, resizable: false, sortable: false, align: "center" },
                       { name: "Description", width: 50, sortable: false },
                       { name: "AccountPlan", width: 80, sortable: false },
                       { name: "Type", width: 20, sortable: false },
                       { name: "Date", width: 20, sortable: false, align: "right" },
                       { name: "Value", width: 30, sortable: false, align: "right" },
                       { name: "canEdit", width: 1, hidden: true }
            ],
            autowidth: true,
            grouping: true, 
            groupingView : { 
                        groupField : ['Type'], 
                        groupColumnShow : [true], 
                        groupText : ['<b>{0}</b>'], 
                        groupCollapse : false, 
                        groupOrder: ['asc'], 
                        groupDataSorted : true 
            },
            gridComplete: function () {
                var rows = $("#releasesGrid").jqGrid('getRowData');

                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i];

                    var accountEntryLink = "<a href='/AccountEntry/Edit/" + row['Id'] + "'>" + row['Description'] + "</a>"
                    $("#releasesGrid").jqGrid('setRowData', row['Id'], { Description: accountEntryLink });
                }
            }
        });

        $("#saveButton").click(function () {
            $("form").submit();
        });

        $("#saveAndOpenLotButton").click(function () {
            $("#SaveAndOpenLote").val('True');
            $("form").submit();
        });

        $("#closeLotMessageContainer").messageContainer({
            icon: 'info',
            message: 'Deseja realmente fechar este lote? <a href="#" id="closeLotYesButton" class="answer-blue">Sim</a> <a href="#" id="closeLotNoButton" class="answer-red">Não</a>'
        });
        $("#closeLotMessageContainer").hide();

        $("#balanceLotMessageContainer").messageContainer({
            icon: 'info',
            message: 'O lote encontra-se desbalanceado. <a href="#" id="hideBalanceLotMessageContainer" class="answer-blue">Ok</a>'
        });
        $("#balanceLotMessageContainer").hide();

        $("#dateInvalidMessageContainer").messageContainer({
            icon: 'alert',
            state: "error",
            message: 'Não é possível criar um lote para a data selecionada, o período já encontra-se fechado.'
        });
        $("#dateInvalidMessageContainer").hide();


        $("#closeLotButton").click(function () {

            if (lotIsBalanced){
                $("#closeLotMessageContainer").show('slow');
            }
            else
            {
                $("#balanceLotMessageContainer").show('slow');
            }

            return false;
        });

        $("#createAccountingEntry").click(function (){
            window.location.href = createAccountingEntryUrl;
        });

        $("#closeLotYesButton").click(function (){
            window.location.href = closeLotUrl;
        });

        $("#closeLotNoButton").click(function (){
            $("#closeLotMessageContainer").hide();
        });

        $("#hideBalanceLotMessageContainer").click(function (){
            $("#balanceLotMessageContainer").hide();
        });

        $("#goBackButton").click(function(){
            window.location.href = goBackUrl;
        });
        
    });
</script>

<style>
    .answer-red{
	    color:red !important;
    }
    
    .answer-blue{
	    color:blue !important;
	    font-weight:bold;
    }
    
    .answer-red, .answer-blue{
        text-decoration: underline;
    }
    
    .ui-progressbar-value { background-image: url(/images/pbar-ani.gif); }
    .no-close .ui-dialog-titlebar-close { display: none }

</style>

<div class="content-left">
    @Html.Partial("ContentLeftPartial")
</div>
<div class="content-right">

<h2>Edit</h2>

<p>
    <button class="button-icon-return-icon-only" id="goBackButton">Voltar</button> | 
    @if (Model.CanSave)
    {
        <button id="saveButton" class="submit">Salvar</button>
    }
    @if (Model.CanSaveAndOpenLote)
    { 
        <button id="saveAndOpenLotButton" class="submit">Salvar e abrir lote</button>
    }
    
    @if (Model.CanCloseLote)
    { 
        <button class="button-red" id="closeLotButton">Fechar lote</button>
    }
    
    @if (Model.CanCreateAccountingEntry)
    { 
            <text>
            | <button class="button-icon-plus" id="createAccountingEntry">Gerar Lançamento Contábil</button>
            </text>
    }
    
</p>

<div id="closeLotMessageContainer"></div>
<div id="balanceLotMessageContainer"></div>
<div id="dateInvalidMessageContainer"></div>

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

        @Html.HiddenFor(model => model.Id)
        @Html.HiddenFor(model => model.SaveAndOpenLote)
        @Html.HiddenFor(model => model.CanSave)
        @Html.HiddenFor(model => model.CanSaveAndOpenLote)
        @Html.HiddenFor(model => model.CanCloseLote)

        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Description, new { placeholder = "Descrição do lote", size = 60 })
            @Html.ValidationMessageFor(model => model.Description)
        </div>
    
        <h3>Período</h3>
        <div class="editor-label">
            <table>
                <tr>
                    <td width="205">@Html.LabelFor(model => model.PeriodStart) @Html.TextBoxFor(model => model.PeriodStart, new { @class = "textBoxReadOnly" }) </td>
                    <td>@Html.LabelFor(model => model.PeriodEnd) @Html.TextBoxFor(model => model.PeriodEnd, new { @class = "textBoxReadOnly" }) </td>
                </tr>
                <tr>
                    <td>
                        <div id="PeriodStartCalendar"></div>
                    </td>
                    <td>
                        <div id="PeriodEndCalendar"></div>
                    </td>
                </tr>
            </table>
        </div>
        
    if (Model.HasOpenDate)
    { 
        <div class="editor-label">
            @Html.LabelFor(model => model.OpenDate) 
            <span class="bold">@Html.DisplayTextFor(model => model.OpenDate)</span>
        </div>
    }
    
    if (Model.HasCloseDate)
    { 
        <div class="editor-label">
            @Html.LabelFor(model => model.CloseDate) 
            <span class="bold">@Html.DisplayTextFor(model => model.CloseDate)</span>
        </div>
    }

    if (Model.HasOpenDate)
    { 
        <h3>Totais</h3>
        <table>
            <tr>
                <td width="205">@Html.LabelFor(model => model.TotalCredit) <span class="bold">@Html.DisplayTextFor(model => model.TotalCredit)</span></td>
                <td>@Html.LabelFor(model => model.TotalDebit) <span class="bold">@Html.DisplayTextFor(model => model.TotalDebit)</span></td>
            </tr>
        </table>
    }
}

@if (Model.HasReleases)
{ 
    <h3>Lançamentos</h3>
    <div class="grid-container" style="padding-right:10px;">
        <table id="releasesGrid">
        </table>
        <div id="releasesPager"></div>
    </div>
}

<p>&nbsp;</p>

</div>